import { defineStore } from "pinia";

//引入统一API
import { resLogin, resUserInfo, resLogout } from "@/api/user/index";
//引入类型
import type {
  LoginForm,
  LoginResponseData,
  UserInfoResponseData,
} from "@/api/user/type";
//引入cloneDeep深拷贝
//@ts-ignore
import cloneDeep from "lodash/cloneDeep";
import type { Info } from "./types/type";
//引入常量路由
import { ConstRouter, anyRouter, asyncRoutes } from "@/router/route";
import router from "@/router";
//引入获取TOKEN方法
import { SET_TOKEN, GET_TOKEN, REMOVE_TOKEN } from "@/utils/token";

//过滤当前用户的路由动态生成组件
function filterRoutes(asyncRoutes: any, routes: any) {
  return asyncRoutes.filter((item: any) => {
    //如果routes包含item的name
    if (routes.includes(item.name)) {
      if (item.children && item.children.length > 0) {
        item.children = filterRoutes(item.children, routes);
      }
      return true;
    }
  });
}
let useUserInfo = defineStore("userInfo", {
  //存储数据的地方
  state: (): Info => {
    return {
      token: GET_TOKEN(),
      MenuRouter: ConstRouter, //存储菜单生成的路由
      username: "",
      avatar: "",
      buttons: [],
    };
  },
  //处理异步或者逻辑的地方
  actions: {
    //登录
    async Login(data: LoginForm) {
      let reslut: LoginResponseData = await resLogin(data);

      if (reslut.code == 200) {
        //登录成功，将用户token存入
        this.token = reslut.data;
        //将token存入本地
        SET_TOKEN(reslut.data);

        return "ok";
      } else {
        //登录失败，提示错误信息
        return Promise.reject(new Error(reslut.data));
      }
    },
    //获取用户信息
    async getUserInfo() {
      let reslut: UserInfoResponseData = await resUserInfo();

      if (reslut.code == 200) {
        this.username = reslut.data.name;
        this.avatar = reslut.data.avatar;
        this.buttons = reslut.data.buttons;
        let asyncroute = filterRoutes(
          cloneDeep(asyncRoutes),
          reslut.data.routes,
        );
        //过滤当前用户的路由动态生成组件
        this.MenuRouter = [...ConstRouter, ...asyncroute, ...anyRouter];
        //动态添加路由
        [...asyncroute, ...anyRouter].forEach((route: any) => {
          router.addRoute(route);
        });
        return "ok";
      } else {
        return Promise.reject(new Error(reslut.message));
      }
    },
    //退出登录
    async logout() {
      let reslut = await resLogout();

      if (reslut.code == 200) {
        //清除token
        REMOVE_TOKEN();
        this.token = "";
        //清除用户信息
        this.username = "";
        this.avatar = "";
        return "ok";
      } else {
        return Promise.reject(new Error(reslut.message));
      }
    },
  },
  //计算属性
  getters: {},
});

export default useUserInfo;
